package com.frogs.ucenter.v1.service.impl.aop;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.ApplicablePlatformEnum;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.system.util.UserIntegralRecordEnum;
import com.frogs.system.util.UserMessageTypeEnum;
import com.frogs.system.util.UserTypeEnum;
import com.frogs.ucenter.component.GivingAsyncHelper;
import com.frogs.ucenter.component.UserMessageDmHelper;
import com.frogs.ucenter.dao.ActionLogDao;
import com.frogs.ucenter.dao.PointTaskCompleteInfoDao;
import com.frogs.ucenter.dao.TaskInfoDao;
import com.frogs.ucenter.dao.UserAccountInfoDao;
import com.frogs.ucenter.dao.UserIntegralBalanceDao;
import com.frogs.ucenter.dao.UserIntegralRecordDao;
import com.frogs.ucenter.dao.UserLevelBufferRecordDao;
import com.frogs.ucenter.dao.UserLevelInfoDao;
import com.frogs.ucenter.dao.UserLevelUpgradeRegulationDao;
import com.frogs.ucenter.dao.UserOrderStatisticsDao;
import com.frogs.ucenter.entity.UserAccountInfo;
import com.frogs.ucenter.entity.UserIntegralBalance;
import com.frogs.ucenter.entity.UserIntegralRecord;
import com.frogs.ucenter.entity.UserLevelBufferRecord;
import com.frogs.ucenter.entity.UserLevelInfo;
import com.frogs.ucenter.entity.UserLevelUpgradeRegulation;
import com.frogs.ucenter.entity.UserOrderStatistics;
import com.frogs.ucenter.v1.util.ApiConstants;
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Component(ApiConstants.VERSION+"baseTaskAop")
public class BaseTaskAop {
	
	private static final Logger log = LoggerFactory.getLogger(BaseTaskAop.class);
	
	@Resource
	private ActionLogDao actionLogDao;
	@Resource
	private UserIntegralRecordDao userIntegralRecordDao;
	@Resource
	private UserIntegralBalanceDao userIntegralBalanceDao;
	@Resource
	private UserAccountInfoDao userAccountInfoDao;
	@Resource
	private UserLevelBufferRecordDao userLevelBufferRecordDao;
	@Resource
	private UserLevelUpgradeRegulationDao userLevelUpgradeRegulationDao;
	@Resource
	private UserOrderStatisticsDao userOrderStatisticsDao;
	@Resource
	private UserLevelInfoDao userLevelInfoDao;
	@Resource
	private UserMessageDmHelper userMessageDmHelper;
	@Resource
	private TaskInfoDao taskInfoDao;
	@Resource
	private PointTaskCompleteInfoDao pointTaskCompleteInfoDao;
	@Resource
	private GivingAsyncHelper givingAsyncHelper;
	
	/**
	 * 评价送积分
	 * 
	 * @param userId
	 * @param orderId
	 * @param buyTime
	 */
	@Async
	public void addUserIntegral(Integer userId, String orderId, String buyTime) {
		// 订单为空
		if (StringUtil.isEmpty(orderId))
			return;
		// 购买时间超过一个月
		if (DateUtil.getDateAfterMonths(DateUtil.parseDate(buyTime, "yyyy-MM-dd"), 1).getTime() < new Date().getTime())
			return;
		UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
		userIntegralRecord.setIntegralNum(5);
		userIntegralRecord.setType(UserIntegralRecordEnum.EVALUATE_DONATE.getId());
		userIntegralRecord.setUserId(userId);
		userIntegralRecord.setRemark("订单号为：" + orderId + ", 评价送积分");
		userIntegralRecordDao.insert(userIntegralRecord);
		UserIntegralBalance userIntegralBalance = userIntegralBalanceDao.selectById(userId);
		if(null == userIntegralBalance){//不存在则进行插入操作
			userIntegralBalance = new UserIntegralBalance();
			userIntegralBalance.setIntegralUsable(5);
			userIntegralBalance.setIntegralUsed(0);
			userIntegralBalance.setId(userId);
			userIntegralBalanceDao.insert(userIntegralBalance);
		}else{//存在则进行更新操作
			int integralUsable = userIntegralBalance.getIntegralUsable();
			userIntegralBalance = new UserIntegralBalance();
			userIntegralBalance.setId(userId);
			userIntegralBalance.setIntegralUsable(integralUsable + 5);
			userIntegralBalanceDao.update(userIntegralBalance);
		}
		
	}
	
	/**
	 * 判断是否添加会员等级降级缓冲期
	 * 
	 * @param userId
	 * @throws Exception 
	 */
	@Async
	public void addUserLevelBufferRecord(Integer userId) throws Exception {
		UserAccountInfo userAccountInfo = userAccountInfoDao.selectById(userId);
		if (userAccountInfo == null)
			return;
		// 邮箱和手机其中绑定一个
		if (userAccountInfo.getIsEmailValid() == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId() 
				||userAccountInfo.getIsPhoneValid() == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId()) {
			return;
		}
		UserLevelInfo userLevelInfo = userLevelInfoDao.selectById(userId);
		if (userLevelInfo.getLevelId() == UserTypeEnum.GENERAL.getType() 
				|| userLevelInfo.getLevelId() == UserTypeEnum.PHARMACIST.getType()
				|| userLevelInfo.getLevelId() == UserTypeEnum.SENIORPHARMACIST.getType()) {
			return;
		}
		UserLevelBufferRecord userLevelBufferRecord = new UserLevelBufferRecord();
		userLevelBufferRecord.setUnbindTime(new Date());
		userLevelBufferRecord.setUserId(userId);
		userLevelBufferRecordDao.insert(userLevelBufferRecord);
		//发送站内短信
		String subject = "降级通知";
		String content = "亲爱的用户，您好！由于您的账号已经解绑了邮箱和手机号码，这会导致您的等级降级，将无法享受当前会员等级福利；"
				+ "如果在7天内，没有重新绑定邮箱和手机号码，7天后会员等级将会降为普通用户。";
		JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();
		object.put("receiver", "");
		object.put("receiverId", userId);
		array.add(object);
		userMessageDmHelper.sendToUser(subject, content, "", "", "系统发送", 
				"-1", array, UserMessageTypeEnum.RECEIVER_PERSONAL.getId(), ApplicablePlatformEnum.WEB.getId());
	}
	
	
	/**
	 * 修改用户等级
	 * 
	 * @param userId
	 * @author wushubin
	 */
	@Async
	public void updateUserLevel(int userId){
		
    	//获取今年订单总数和订单总额
    	Map<String , Object> userOrderStatisticsParams = new HashMap<String , Object>();
    	userOrderStatisticsParams.put("eqUserId", userId);
    	userOrderStatisticsParams.put("eqOrderYear",DateUtil.getYear(new Date()) );
    	PageList<UserOrderStatistics> userOrderStatisticsList = userOrderStatisticsDao.selectByMap(userOrderStatisticsParams, 1, 1, false);
    	if(userOrderStatisticsList.size() == 0)
    		return ;
    	
    	UserLevelUpgradeRegulation userLevelUpgradeRegulation = getUserLevelUpgradeRegulation(userOrderStatisticsList.get(0));
    	if(userLevelUpgradeRegulation != null){
    		if(isExistContactWay(userLevelUpgradeRegulation, userId)){
	    		this.updateUserLevelInfo(userId, userLevelUpgradeRegulation.getId());
    		}
    	}
	}
	
	/**
	 * 获取会员等级
	 * @param userOrderStatistics
	 * @return
	 */
	private UserLevelUpgradeRegulation getUserLevelUpgradeRegulation(UserOrderStatistics userOrderStatistics){
		//查询对应的会员等级规则
    	Map<String , Object> userLevelUpgradeRegulationParams = new HashMap<String , Object>();
    	userLevelUpgradeRegulationParams.put("gtOrderSumNum",userOrderStatistics.getOrderNum());
    	userLevelUpgradeRegulationParams.put("ltOrderSumNum",userOrderStatistics.getOrderNum());
    	
    	userLevelUpgradeRegulationParams.put("gtOrderSumMoney",userOrderStatistics.getMoney());
    	userLevelUpgradeRegulationParams.put("ltOrderSumMoney",userOrderStatistics.getMoney());
    	UserLevelUpgradeRegulation userLevelUpgradeRegulation = userLevelUpgradeRegulationDao.selectByData(userLevelUpgradeRegulationParams);
    	return userLevelUpgradeRegulation;
	}
	
	/**
	 * 查询用户是否有绑定手机和邮箱
	 * 注意：如果绑定了，就删除用户的解绑记录
	 * @param userLevelUpgradeRegulation
	 * @param userId
	 * @return
	 */
	private boolean isExistContactWay (UserLevelUpgradeRegulation userLevelUpgradeRegulation , Integer userId){
		
		if(userLevelUpgradeRegulation.getIsExistContactWay() == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId()){
			UserAccountInfo userAccountInfo = userAccountInfoDao.selectById(userId);
			//检查是否有绑定
			if(userAccountInfo.getIsEmailValid() == UserAccountInfoStatusEnum.AVAILABILITY_NO.getId() &&
    			userAccountInfo.getIsPhoneValid() == UserAccountInfoStatusEnum.AVAILABILITY_NO.getId()){
				return false;
			}
			else{
				//有绑定，则删除解绑记录
				Map<String, Object> params = new HashMap<String,Object>();
				params.put("eqUserId", userId);
				userLevelBufferRecordDao.deleteByMap(params);
				return true;
			}
		}
		return true;
	}
	
	/**
	 * 修改会员等级，此处只考虑升级，不考虑降级修改
	 * @param userId
	 * @param levelId
	 */
	private void updateUserLevelInfo(Integer userId ,Integer levelId){
		UserLevelInfo userLevelInfo = userLevelInfoDao.selectById(userId);
		if(userLevelInfo.getLevelId() < levelId){
    		userLevelInfo.setLevelId(levelId);
    		userLevelInfoDao.update(userLevelInfo);
		}
	}
}
